package com.sms.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class GetPeopleServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		int level = Integer.parseInt(request.getParameter("level"));
		int proID = Integer.parseInt(request.getParameter("proID"));
		
		System.out.println(level);
		
		List<Student> slist = new ArrayList<Student>();
		List<Student> llist = null;
		List<Teacher> tlist = null;
		slist = User.getAllStudents(proID);//包含组员与组长
		
		if(level == 2) {//两级时向老师及成员交流信息
			tlist = new ArrayList<Teacher>();
			tlist = User.getTeacher(proID);
		} else {//3级时还要向组长交流
			llist = new ArrayList<Student>();
			llist = User.getLeaderStudent(proID);
		}
		
		if (slist != null && slist.size() > 0) {
			JSONArray json = new JSONArray();
			
			String leaderID = "";
			if(level == 3 && llist != null && llist.size() > 0) {
				leaderID = llist.get(0).getSno();
			}
			
			for (int i = 0; i < slist.size(); i++) {
				Student s = (Student) slist.get(i);
				JSONObject j = new JSONObject();
				String sno = s.getSno();
				if(level == 3 && sno.equals(leaderID)) {
					j.put("pno", sno);
					j.put("pname", s.getSname()+ "[组长]");
				} else {
					j.put("pno", sno);
					j.put("pname",s.getSname() );
				}
				json.add(j);
			}
			
			//2级时添加老师
			if(level == 2 && tlist != null && tlist.size() > 0) {
				for(int i=0; i<tlist.size(); i++) {
					Teacher t = (Teacher)tlist.get(i);
					JSONObject j = new JSONObject();
					j.put("pno", t.getTno());
					j.put("pname",t.getTname() + "[老师]");
					json.add(j);
				}
			}
			out.println(json);
		} else {
			System.out.println("没有学生可选择");
		}
		
		out.flush();
		out.close();
	}


}
